<?php
class UserController extends Zend_Controller_Action{
	protected $_model = null;
	public function init(){
		$this->_model = new Application_Model_DbTable_User();
		$this->view->layout()->placeholders = array(
				'slider'=>array('status'=>false,'content'=>''),
				'search'=>array('status'=>false,'content'=>'')
						
		);
		
	}
	
	public function indexAction(){
		
	}
	
	public function loginAction(){
		$this->view->headTitle()->prepend('Đăng Nhập');
		
		$this->_helper->layout()->setLayout('login');
		$this->_helper->layout()->setLayoutPath(APPLICATION_PATH.'/layouts/default');
		
		$form = new Default_Form_Login();
		$form->setAction($this->view->baseUrl('/'.LANG.'/thanh-vien/dang-nhap.html'));
		$auth = Zend_Auth::getInstance();
		
		//nếu đã login rồi thì chuyển vào trang trang index
		

		$errors = array();
		//nếu bắt đầu đăng nhập
		if($this->_request->isPost()){
				
			//lấy giá trị username và password
			$email = $this->_request->getParam('email');
			$password = $this->_request->getParam('password');
				
			//thiết lập adapter với table, column để kiểm tra
			$adapter = new Zend_Auth_Adapter_DbTable();
			$adapter->setTableName('tbl_user');
			$adapter->setIdentityColumn('user_email');
			$adapter->setCredentialColumn('user_password');
			$adapter->setCredentialTreatment('MD5(?) and user_status = 1');
				
			//gán giá trị
			if(trim($email)=="" || trim($password)==""){
				$errors[]="Đăng nhập thất bại";
			}else{
				$adapter->setIdentity($email);
				$adapter->setCredential($password);
				$result = $auth->authenticate($adapter);
				if ($result->isValid ()) {
					$user = $adapter->getResultRowObject ( null, array () );
					$auth->getStorage ()->write ( $user );
					
					//ghi nho
					//Zend_Session::rememberMe();
				}else{
					$errors[]="Đăng nhập thất bại";
				}			
			}
		}
		
		if($auth->hasIdentity()){
			$this->_redirect('/'.LANG);
		}
		$this->view->errors=$errors;
		$this->view->form = $form;
	}
	
	public function logoutAction(){
		$auth = Zend_Auth::getInstance ();
		if ($auth->hasIdentity ()) {
			$auth->clearIdentity ();
			$this->_redirect ("/");
		}
	}
	
	public function registerAction(){
		$form = new Default_Form_Register();
		//$captcha = new Cms_Captcha_Image();
		//$form->getElement('captcha_id')->setValue($captcha->getId());
		$message = "";
		if($this->_request->isPost()){

			if($form->isValid($_POST)){
// 				$captchaID = $this->_request->getParam('captcha_id');
// 				$captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_'.$captchaID);
// 				$captchaWord = $captchaSession->word;
// 				$captcha->removeCaptcha($captchaID);
// 				if($this->_request->getParam("captcha_text") != $captchaWord){
// 					//$form->getElement('captcha_text')->addError('Nhập mã bảo vệ không chính xác!');
// 					$form->markAsError();
// 					$message='mã bảo vệ không chính xác';	
// 					$this->view->msgStatus = 'error';
// 				}		
				
				
				//kiem tra mat khau va mat khau nhap lai
				if($form->getValue('user_password') != $form->getValue('user_password_retype')){
					$form->getElement('user_password')->addError('Mật khẩu nhập lại không chính xác');
					$form->markAsError();
				}
				
				//check email
				$check = $this->_model->fetchAll($this->_model->select()->where('user_email = ?',$form->getValue('user_email')));
			
				if(count($check)>0){
					$form->getElement('user_email')->addError('Email này đã được sử dụng, vui lòng chọn email khác!');
					$form->markAsError();
				}
				
				if(!$form->hasErrors()){
					$row = $this->_model->createRow($_POST);
					$row->user_status = 1;
					
					$row->user_password = md5($form->getValue('user_password'));
					//set quyền thành viên
					$row->user_group_user_id = 3;
					
					//lưu
					$row->save();
					$message="Đăng ký thành công!";
					$this->_helper->flashMessenger->addMessage('Đăng ký thành công!');
					$this->_redirect('/'.LANG.'/thong-bao.html');
				}
			}//end check valid
			else{
				//var_dump($form->getMessages());
			}
			//$captcha->get
		}//end post
		
		$this->view->form = $form;
		$this->view->message = $message;
	}
	
	public function profileAction(){
		$form = new Default_Form_User();
		$auth = Zend_Auth::getInstance();
		$id = $auth->getIdentity()->user_id;
		$row = $this->_model->find($id)->current();
		$message = '';
		if($this->_request->isPost()){
			if($form->isValid($_POST)){
				$row->user_fullname = $form->getValue('user_fullname');
				$row->user_address = $form->getValue('user_address');
				$row->user_phone = $form->getValue('user_phone');
				$row->save();
				$message = 'cập nhật thành công';
			}
		}
		
		$form->populate($row->toArray());		
		$this->view->form = $form;
		$this->view->message = $message;
	}
	
	public function changepassAction(){
		$form = new Default_Form_Changepass();
		$message = '';
		$this->view->form = $form;
		if($this->_request->isPost()){
			if($form->isValid($_POST)){
				
				$auth = Zend_Auth::getInstance();
				$id = $auth->getIdentity()->user_id;
				$row = $this->_model->find($id)->current();
				
				if(md5($form->getValue('password')) != $row->user_password ){
					$form->getElement('password')->addError('Mật khẩu không đúng');
					$form->markAsError();
				}
				
				if($form->getValue('new_password') != $form->getValue('new_password_retype')){
					$form->getElement('new_password_retype')->addError('Mật khẩu nhập lại không đúng');
					$form->markAsError();
				}
				
				if(!$form->hasErrors()){
					$row->user_password = md5(trim($form->getValue('new_password')));
					$row->save();
// 					echo '<script>alert("Cập nhật thành công!")</script>';
					$message = 'cập nhật thành công';
				}
				
			}//end if form check
		}//end if request
		$this->view->message = $message;
		
	}
	
	public function orderAction(){
		$mdOrder = new Application_Model_DbTable_Order();
		
		//get item count per page
		$icpp = $this->_request->getParam('icpp',20);
		
		//get current page number
		$currentPage = $this->_request->getParam('page',1);
		
		//current user
		$auth = Zend_Auth::getInstance();
		$id = $auth->getIdentity()->user_id;
		$select = $mdOrder->select()->where('order_user_id = ?',$id)
			->order('order_creation_time desc');
		$list = $mdOrder->fetchAll($select)->toArray();
		// pagination
		$paginator = Zend_Paginator::factory($list);
		$paginator->setCurrentPageNumber($currentPage);
		$paginator->setItemCountPerPage($icpp);
		$paginator->setPageRange(5);
		
		//assign to view
		$this->view->paginator=$paginator;
	}
	
	public function orderdetailAction(){
		$id = $this->_request->getParam('id');
		$mdOrderDetail = new Application_Model_DbTable_OrderDetail();
		$rows = $mdOrderDetail->fetchAll($mdOrderDetail->select()->where('order_detail_order_code = ?',$id));
		if($rows){
			$this->view->orderdetail = $rows;
		}
	}
	
	public function receiveemailAction(){
		$errorMessage = 'Đăng kí thành công!';
		$email = $this->_request->getParam('email');
		$validEmail = new Zend_Validate_EmailAddress();		
		if(trim($email)==''){
			$errorMessage = 'Vui lòng nhập email';
		}
		elseif(!$validEmail->isValid($email)){
			$errorMessage = 'Email không hợp lệ';
		}else{
			$mdReceiveEmail = new Application_Model_DbTable_ReceiveEmail();
			$row = $mdReceiveEmail->fetchRow($mdReceiveEmail->select()->where('receive_email_address = ?',$email));
			
			//nếu là email đã đăng kí
			if($row){
				$row->receive_email_status=1;
			}else{
				$row = $mdReceiveEmail->createRow();
				$row->receive_email_address = $this->_request->getPost('email');
				$row->receive_email_status = 1;
				$row->save();
			}
		}
		$this->_helper->layout()->disableLayout(true);
		$this->_helper->json->sendJson($errorMessage);
	}
}














